﻿using System;
using System.Windows;
using TicTacToe.Core;

namespace _3DTicTacToe.UI
{
    partial class NewGameDialog : Window
    {
        private bool _playerOneValid, _playerTwoValid;
        bool AllValid { get { return _playerOneValid && _playerTwoValid; } }

        public NewGameDialog()
        {
            InitializeComponent();

            var rng = new Random();
            firstPlayerCBox.SelectedIndex = rng.Next(0, 2);

            playerOneControl.SelectedColorIndex = 11;
            playerTwoControl.SelectedColorIndex = 32;

            playerOneControl.PlayerPropsChanged += playerOneControl_PlayerPropsChanged;
            playerTwoControl.PlayerPropsChanged += playerTwoControl_PlayerPropsChanged;

            startButton.IsEnabled = false;
        }

        void playerOneControl_PlayerPropsChanged(bool valid)
        {
            _playerOneValid = valid;
            startButton.IsEnabled = AllValid;

            if (valid) playerOneCBItem.Content = playerOneControl.PlayerName;
        }

        void playerTwoControl_PlayerPropsChanged(bool valid)
        {
            _playerTwoValid = valid;
            startButton.IsEnabled = AllValid;

            if (valid) playerTwoCBItem.Content = playerTwoControl.PlayerName;
        }

        private void startButton_Click(object sender, RoutedEventArgs e)
        {
            var p1 = playerOneControl.Player;
            var p2 = playerTwoControl.Player;

            var game = firstPlayerCBox.SelectedIndex == 0
                           ? new TicTacToeGame(p1, p2)
                           : new TicTacToeGame(p2, p1);

            new GameWindow(game).Show();
            Close();
        }
    }
}
